package com.haoqizhe.kernel.redis.config;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

import java.nio.charset.Charset;

/**
 * 自定义redis的序列化方式，将对象序列化为json字符串
 *
 * @author yam.qiu
 * @date 2019/2/14 9:51
 */
@Slf4j
public class CustomSerializer implements RedisSerializer<Object> {

    static final byte[] EMPTY_ARRAY = new byte[0];
    private final Charset charset;

    public CustomSerializer() {
        this(Charset.forName("UTF8"));
    }

    public CustomSerializer(Charset charset) {
        this.charset = charset;
    }

    @Override
    public byte[] serialize(Object o) throws SerializationException {
        try {
            String jsonString = JSONUtil.toJsonStr(o);
            return (jsonString == null ? EMPTY_ARRAY : jsonString.getBytes(charset));
        } catch (Exception ex) {
            log.error("redis序列化失败", ex);
        }
        return null;
    }

    @Override
    public Object deserialize(byte[] bytes) throws SerializationException {
        String objStr = null;
        if (bytes == null) {
            return objStr;
        }
        try {
            objStr = new String(bytes, charset);
        } catch (Exception ex) {
            log.error("redis反序列失败", ex);
        }
        return objStr;
    }
}
